WebSocket 用來建立給伺服器推播訊息用的通道,以利即時的訊息廣播
在 Golang 中實作簡單的 WebSocket
package main
import (
"html/template"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var err error
func main() {
http.Handle("/", http.HandlerFunc(indexHandler))
http.Handle("/ws", http.HandlerFunc(wsHandler))
http.ListenAndServe(":3000", nil)
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
if err != nil {
http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
}
go echo(c)
}
func echo(c *websocket.Conn) {
for {
if err = c.WriteJSON("hello world"); err != nil {
log.Println(err)
}
time.Sleep(time.Second)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("helloworld.html")
t.Execute(w, "Hello World!")
}
依賴了 gorilla/websocket
來實作 WebSocket 伺服器端的邏輯,
透過 websocket.Upgrade
產生連線的實體,
在 go echo(c)
中每秒向瀏覽器端發送訊息,
建立起簡單的 WebSocket。
<html>
<head>
<title>websocket example</title>
</head>
<body>
{{ . }}
<script type="text/javascript">
var ws;
if (window.WebSocket === undefined) {
alert("Your browser does not support WebSockets.");
} else {
ws = initWS();
}
function initWS() {
var socket = new WebSocket("ws://localhost:3000/ws");
socket.onopen = function () {
console.log("Socket is open.");
};
socket.onmessage = function (e) {
console.log("Received data.", e.data);
}
socket.onclose = function () {
console.log("Socket closed.");
setTimeout(function () {
initWS()
}, 5000);
}
return socket;
}
</script>
</body>
</html>
在前端的部分利用 原生的 WebSocket API,建立通道,等待伺服器的推播。